package com.vpx.server.service.system.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vpx.server.bean.entity.ProjectConfig;
import com.vpx.server.bean.entity.Template;
import com.vpx.server.bean.entity.TemplateAttr;
import com.vpx.server.bean.order.base.BaseDelOrder;
import com.vpx.server.bean.order.base.BaseIdStrOrder;
import com.vpx.server.bean.order.system.ProjectConfigOrder;
import com.vpx.server.bean.order.system.TemplateAttrOrder;
import com.vpx.server.bean.order.system.TemplateAttrPageOrder;
import com.vpx.server.bean.result.system.TemplateAttrPageResult;
import com.vpx.server.bean.result.system.TemplateAttrResult;
import com.vpx.server.bean.result.system.TemplatePageResult;
import com.vpx.server.bean.result.system.TemplateResult;
import com.vpx.server.framework.base.ResultMsg;
import com.vpx.server.framework.utils.DateUtils;
import com.vpx.server.mapper.system.TempalteAttrMapper;
import com.vpx.server.mapper.system.TemplateMapper;
import com.vpx.server.service.system.SqlExtService;
import com.vpx.server.service.system.SqlService;
import com.vpx.server.service.system.TemplateAttrService;
import com.vpx.server.service.system.TemplateService;
import com.vpx.server.utils.UserLoginUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author PC
 * @Date 2023/11/18 16:31
 **/
@Service
public class TemplateAttrServiceImpl extends ServiceImpl<TempalteAttrMapper, TemplateAttr> implements TemplateAttrService {
    @Resource
    private SqlExtService sqlExtService;
    @Resource
    SqlService sqlService;
    @Override
    public ResultMsg saveTemplateAttr(TemplateAttrOrder order) {
        TemplateAttr entity = new TemplateAttr();
        BeanUtil.copyProperties(order,entity);
        entity.setCreateUser(UserLoginUtils.getCurrentUser() == null ? "admin" : UserLoginUtils.getCurrentUser().getId().toString());
        entity.setCreateTime(DateUtils.getDateTimeStr());
        baseMapper.insert(entity);
        return ResultMsg.success();
    }

    @Override
    public ResultMsg deleteTemplateAttr(BaseDelOrder order) {
        baseMapper.deleteById(order.getId());
        return ResultMsg.success();
    }

    @Override
    public ResultMsg updateTemplateAttrById(TemplateAttrOrder order) {
        if (StrUtil.isEmpty(order.getId())){
            return ResultMsg.fail("数据id不能为空");
        }
        TemplateAttr template = baseMapper.selectById(order.getId());
        if (template == null){
            return ResultMsg.fail("数据不存在，请刷新重试");
        }
        BeanUtil.copyProperties(order,template);
        updateById(template);
        return ResultMsg.success();
    }

    @Override
    public ResultMsg<TemplateAttrResult> selectTemplateAttrById(BaseIdStrOrder order) {
        if (StrUtil.isEmpty(order.getId())){
            return ResultMsg.fail("数据id不能为空");
        }
        TemplateAttr template = baseMapper.selectById(order.getId());
        if (template == null){
            return ResultMsg.fail("数据不存在，请刷新重试");
        }
        TemplateAttrResult result = new TemplateAttrResult();
        BeanUtil.copyProperties(template,result);
        return ResultMsg.success(result);
    }

    @Override
    public ResultMsg<TemplateAttrPageResult> pageQueryTemplate(TemplateAttrPageOrder order) {
        PageHelper.startPage(order.getPageNum(), order.getPageSize());
        QueryWrapper<TemplateAttr> wrapper = new QueryWrapper();
        wrapper.like(StrUtil.isNotBlank(order.getAttrName()),"attr_name",order.getAttrName());
        wrapper.like(StrUtil.isNotBlank(order.getAttrCode()),"attr_code",order.getAttrCode());
        wrapper.like(StrUtil.isNotBlank(order.getAttrRange()),"attr_range",order.getAttrRange());
        wrapper.eq(StrUtil.isNotBlank(order.getAttrType()),"attr_type",order.getAttrType());
        wrapper.eq(StrUtil.isNotBlank(order.getTemplateId()),"template_id",order.getTemplateId());
        List<TemplateAttr> projects = this.list(wrapper);
        PageInfo<TemplateAttr> pageInfo = new PageInfo<>(projects);
        PageInfo<TemplateAttrResult> pageInfo2 = new PageInfo<>();
        BeanUtil.copyProperties(pageInfo,pageInfo2);
        TemplateAttrPageResult result = new TemplateAttrPageResult();
        result.setPageInfo(pageInfo2);
        return ResultMsg.success(result);
    }

    @Override
    public void batchSaveUpdate(List<TemplateAttrOrder> attrOrders,String templateId,boolean updateFlag) {
        QueryWrapper<TemplateAttr> wrapper = new QueryWrapper<>();
        wrapper.eq("template_id",templateId);
        if (CollUtil.isEmpty(attrOrders)){
            //删除所以属性
            List<String> delIds =  this.sqlExtService.findListObject("select id from c_template_attr where template_id = '"+templateId+"'", String.class);
            baseMapper.delete(wrapper);
            if(updateFlag) {//当前操作为更新操作
                List<JSONObject> execObjs = new ArrayList<>();
                if(delIds.size() > 0) {
                    delIds.forEach(delId->{
                        JSONObject obj = JSONUtil.createObj();
                        obj.putByPath("id", IdUtil.getSnowflakeNextIdStr());
                        obj.putByPath("template_id", templateId);
                        obj.putByPath("template_attr_id", delId);
                        obj.putByPath("add_type", "2");
                        obj.putByPath("create_time", DateUtils.getDateTimeStr());
                        execObjs.add(obj);
                    });
                }
                if(execObjs.size() > 0) {
                    Map<String, Object> param = new HashMap<>();
                    param.put("list", execObjs);
                    sqlService.execute("24033101", param);
                }
            }
        } else {

            List<TemplateAttr> listAll = list(wrapper);

            Map<String, TemplateAttrOrder> updateMap = attrOrders.stream().filter(e -> StrUtil.isNotBlank(e.getId())).collect(Collectors.toMap(e -> e.getId(), e -> e));

            //修改数据
            List<TemplateAttr> updateList = new ArrayList<>();
            Iterator<TemplateAttr> iterator = listAll.iterator();
            while (iterator.hasNext()){
                TemplateAttr next = iterator.next();
                if (updateMap.get(next.getId()) != null){
                    TemplateAttrOrder configOrder = updateMap.get(next.getId());
                    BeanUtil.copyProperties(configOrder,next);
                    updateList.add(next);
                    iterator.remove();
                }
            }
            //新增数据
            List<TemplateAttr> addList = new ArrayList<>();
            List<String> addIds = new ArrayList<>();
            attrOrders.stream().forEach(o -> {
                if (StrUtil.isEmpty(o.getId())){
                    TemplateAttr entity = new TemplateAttr();
                    BeanUtil.copyProperties(o,entity);
                    entity.setCreateUser(UserLoginUtils.getCurrentUser() == null ? "admin" : UserLoginUtils.getCurrentUser().getId().toString());
                    entity.setCreateTime(DateUtils.getDateTimeStr());
                    addList.add(entity);
                }
            });
            if (CollUtil.isNotEmpty(updateList)){
                updateBatchById(updateList);
            }
            List<String> allIds =  this.sqlExtService.findList("select id from c_template_attr where template_id = '"+templateId+"'", String.class);
            if (CollUtil.isNotEmpty(addList)){
                saveBatch(addList);
                if(updateFlag) {//当前操作为更新操作
                    String addSql = "select id from c_template_attr where template_id = '"+templateId+"'";
                    if(allIds.size() > 0) {
                        addSql = addSql + " and id not in ('" + StrUtil.join("','",allIds) + "')";
                    }
                    addIds = this.sqlExtService.findList(addSql, String.class);
                }
            }
            List<String> delIds = new ArrayList<>();
            if (CollUtil.isNotEmpty(listAll)){
                delIds = listAll.stream().map( e-> e.getId()).collect(Collectors.toList());
                baseMapper.deleteBatchIds(delIds);
            }
            if(updateFlag) {//当前操作为更新操作
                List<JSONObject> execObjs = new ArrayList<>();
                if(addIds.size() > 0) {
                    addIds.forEach(addId->{
                        JSONObject obj = JSONUtil.createObj();
                        obj.putByPath("id", IdUtil.getSnowflakeNextIdStr());
                        obj.putByPath("template_id", templateId);
                        obj.putByPath("template_attr_id", addId);
                        obj.putByPath("add_type", "1");
                        obj.putByPath("create_time", DateUtils.getDateTimeStr());
                        execObjs.add(obj);
                    });
                }
                if(delIds.size() > 0) {
                    delIds.forEach(delId->{
                        JSONObject obj = JSONUtil.createObj();
                        obj.putByPath("id", IdUtil.getSnowflakeNextIdStr());
                        obj.putByPath("template_id", templateId);
                        obj.putByPath("template_attr_id", delId);
                        obj.putByPath("add_type", "2");
                        obj.putByPath("create_time", DateUtils.getDateTimeStr());
                        execObjs.add(obj);
                    });
                }
                if(execObjs.size() > 0) {
                    Map<String, Object> param = new HashMap<>();
                    param.put("list", execObjs);
                    sqlService.execute("24033101", param);
                }
            }
        }

    }
}
